package com.it.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.it.entity.*;
import com.it.service.InventoryService;
import com.it.service.OrderService;
import com.it.service.ProductService;
import com.it.service.UserService;
import com.it.util.ItdragonUtils;
import com.it.util.Result;
import com.it.util.ResultResponse;
import com.it.util.TableResultResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 〈订单实现接口〉<br>
 * @since 1.0.0
 */
@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ItdragonUtils itdragonUtils;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;

    /**
     * 管理界面跳转
     *
     * @param mv
     * @return
     */
    @RequestMapping("/index.do")
    public ModelAndView enIndex(ModelAndView mv) {
        mv.setViewName("order/index");
        return mv;
    }

    /**
     * 订单列表加载接口
     *
     * @param orderFrom
     * @param page
     * @param limit
     * @return
     */
    @ResponseBody
    @GetMapping("orderTable.do")
    public TableResultResponse orderTable(OrderFrom orderFrom, int page, int limit) {
        List<Map<String, Object>> infoList = new ArrayList<>();
        Page<OrderFrom> pageInfo = orderService.selectPage(orderFrom, page, limit);
        for (OrderFrom record : pageInfo.getRecords()) {
            Map<String, Object> resultMap = new HashMap<>(16);
            resultMap.put("id", record.getId());
            resultMap.put("userId", record.getUserId());
            resultMap.put("address", record.getAddress());
            resultMap.put("price", "￥" + record.getPrice());
            resultMap.put("status", record.getStatus());
            resultMap.put("content", record.getContent());
            resultMap.put("mode", record.getMode());
            //拿到提醒信息
            List<Logistics> remind = orderService.getRemind(record.getId(), "remind");
            if (!remind.isEmpty()) {
                resultMap.put("remind", " <span onclick='reminds(\"" + record.getId() + "\",\"" + remind.get(0).getTime() + "\")'  style=\"color:red;cursor: pointer\">用户提醒发货<span class=\"layui-badge-dot\"></span></span>");
            } else {
                resultMap.put("remind", "暂无提醒");
            }
            resultMap.put("timestamp", record.getTime() == null ? "" : record.getTime().substring(0, 19));
            resultMap.put("uuId", " <a href=\"/order/details.do?orderId=" + record.getId() + "\" style=\"color:#009fff\">" + record.getUuId() + "</a>");
            infoList.add(resultMap);
        }
        return Result.tableResule(pageInfo.getTotal(), infoList);
    }

    /**
     * 删除提醒
     *
     * @param orderId
     * @return
     */
    @ResponseBody
    @DeleteMapping("/delRemind.do")
    public ResultResponse delRemind(String orderId) {
        boolean result = orderService.deleteRemind(orderId);
        if (!result) {
            return Result.resuleError("操作失败");
        }
        return Result.resuleSuccess();
    }

    /**
     * 订单详情页面
     *
     * @param mv
     * @return
     */
    @RequestMapping("/details.do")
    public ModelAndView details(ModelAndView mv, String orderId) {
        mv.addObject("orderId", orderId);
        mv.setViewName("order/details");
        return mv;
    }

    /**
     * 删除订单
     *
     * @param id
     * @return
     */
    @ResponseBody
    @DeleteMapping("/order.do")
    public ResultResponse delClassify(String id) {
        boolean result = orderService.delById(id);
        if (!result) {
            return Result.resuleError("删除失败");
        }
        return Result.resuleSuccess();
    }

    /**
     * 编辑订单
     *
     * @param orderFrom
     * @return
     */
    @ResponseBody
    @PutMapping("/order.do")
    public ResultResponse updataClassify(OrderFrom orderFrom) {
        boolean result = orderService.edit(orderFrom);
        if (!result) {
            return Result.resuleError("编辑失败");
        }
        return Result.resuleSuccess();
    }

    /**
     * 添加物流信息页面
     *
     * @param mv
     * @return
     */
    @RequestMapping("/addLogisticsPage.do")
    public ModelAndView addLogisticsPage(ModelAndView mv, String orderId) {
        mv.addObject("orderId", orderId);
        mv.setViewName("order/addLogistics");
        return mv;
    }

    /**
     * 添加物流信息
     *
     * @param orderId
     * @return
     */
    @ResponseBody
    @PostMapping("/addLogistics.do")
    public ResultResponse addLogistics(String orderId, String content) {
        boolean b = orderService.addLogistics(orderId, content);
        if (b) {
            return Result.resuleSuccess();
        }
        return Result.resuleError("添加失败!");
    }

    /**
     * 查看物流信息
     *
     * @param mv
     * @return
     */
    @RequestMapping("/lookLogistics.do")
    public ModelAndView lookLogistics(ModelAndView mv, String orderId) {
        List<Logistics> logisticsList = orderService.getRemind(orderId, "logistics");
        mv.addObject("logisticsList", logisticsList);
        mv.setViewName("order/lookLogistics");
        return mv;
    }

    /**
     * 商品评价
     *
     * @param orderId
     * @return
     */
    @ResponseBody
    @PostMapping("/addEvaluate.do")
    public ResultResponse addEvaluate(String orderId, String score, String content) {
        boolean b = orderService.addLogistics(orderId, content);
        if (b) {
            return Result.resuleSuccess();
        }
        return Result.resuleError("添加失败!");
    }

    /**
     * 退货管理页面
     *
     * @param mv
     * @return
     */
    @RequestMapping("/salesReturnPage.do")
    public ModelAndView salesReturnPage(ModelAndView mv) {
        mv.setViewName("order/salesReturn");
        return mv;
    }

    @ResponseBody
    @GetMapping("salesReturnTable.do")
    public TableResultResponse salesReturnTable(SalesReturn salesReturn, int page, int limit) {
        List<Map<String, Object>> infoList = new ArrayList<>();
        Page<SalesReturn> pageInfo = orderService.selectPage(salesReturn, page, limit);
        for (SalesReturn record : pageInfo.getRecords()) {
            Map<String, Object> resultMap = new HashMap<>(16);
            resultMap.put("id", record.getId());
            resultMap.put("userName", record.getUserName());
            resultMap.put("orderUuId", record.getOrderUuId());
            resultMap.put("orderId", record.getOrderId());
            resultMap.put("reason", record.getReason());
            resultMap.put("time", record.getTime() == null ? "" : record.getTime().substring(0, 19));
            infoList.add(resultMap);
        }
        return Result.tableResule(pageInfo.getTotal(), infoList);
    }

    /**
     * 同意退货
     *
     * @param id
     * @return
     */
    @ResponseBody
    @DeleteMapping("/delSalesReturn.do")
    public ResultResponse delSalesReturn(String id, String orderId) {
        boolean result = orderService.delSalesById(id, orderId);
        if (!result) {
            return Result.resuleError("删除失败");
        }
        OrderDetails orderDetails = new OrderDetails();
        orderDetails.setOrderId(orderId);
        List<OrderDetails> orderDetailsList = orderService.selectPage(orderDetails);
        for (OrderDetails details : orderDetailsList) {
            inventoryService.editStock(details.getProductId(), -details.getProductNum());
        }
        //退还余额
        OrderFrom orderFrom = orderService.getOrderFrom(orderId);
        User user = userService.selectByPrimaryKey(orderFrom.getUserId());
        user.setBalance(user.getBalance() + orderFrom.getPrice());
        userService.updateByPrimaryKey(user);
        return Result.resuleSuccess();
    }

    /**
     * 生成订单页面
     *
     * @param mv
     * @return
     */
    @RequestMapping("/salePage.do")
    public ModelAndView salePage(ModelAndView mv) {
        mv.setViewName("order/salePage");
        return mv;
    }

    /**
     * 生成订单功能
     *
     * @param productUuid
     * @param number
     * @return
     */
    @ResponseBody
    @PostMapping("/sale.do")
    public ResultResponse sale(String productUuid, String number, String mode, String content, String address) {
        ///通过商品编号查询商品不存在返回false
        Product product = productService.getOneByuuId(productUuid);
        if (product == null) {
            return Result.resuleError("商品不存在!");
        }
        List<Inventory> inventories = inventoryService.getOneByProductId(product.getId());
        if (inventories.isEmpty()) {
            return Result.resuleError("库存不足!");
        } else {
            if (inventories.get(0).getStock() < Integer.parseInt(number)) {
                return Result.resuleError("库存不足!");
            }
        }
        boolean settle = orderService.sale(product.getId(), number, address, mode, content);
        if (settle) {
            //库存数减少
            inventoryService.editStock(product.getId(), Integer.parseInt(number));
            //生成出库信息
            OutInventory outInventory = new OutInventory();
            outInventory.setProductName(product.getName());
            outInventory.setProductUuid(product.getUuId());
            outInventory.setNumber(Integer.parseInt(number));
            outInventory.setTotalPrice(product.getPrice() * Float.parseFloat(number));
            outInventory.setUnitPrice(product.getPrice());
            inventoryService.insert(outInventory);
            return Result.resuleSuccess();
        } else {
            return Result.resuleError("提交失败!");
        }


    }
}